#!/usr/bin/python


#    This file is part of CamVue.
#
#    CamVue is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    CamVue is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with CamVue.  If not, see <http://www.gnu.org/licenses/>.

#    Copyright 2012  Jeremy Mortis (mortis@tansay.ca)

# A layer on top of the vidcap module:
# http://videocapture.sourceforge.net/ 

import logging
import sys
import vidcap
import Image
import StringIO
import time

#--------------------------------------------------------------------
class Camera:
    def __init__(self, id=0, width=320, height=240):

        self.id = id
        self.device = None
        self.width = width
        self.height = height
                
        if sys.platform != 'win32':
            raise Exception("This driver for Windows only (not %s)" % sys.platform)

        logging.info('Opening device %s' % self.id)

        self.device=vidcap.new_Dev(int(id), False)

        logging.debug('device %s opened'%self.id)

        self.startTime=time.time()
        self.imagesRead = 0

    def getImage(self):
        buffer, width, height = self.device.getbuffer()
        self.imagesRead += 1
        return Image.fromstring('RGB', (width, height), buffer, 'raw', 'BGR', 0, -1)
    
    def properties(self):

        try:
            self.device.displaycapturepinproperties()
        except:
            pass

        try:
            self.device.displaycapturefilterproperties()
        except:
            pass

    def getProperties(self):
        p = {}
        p["DisplayName"] = self.device.getdisplayname()
        return p

    def close(self):
        self.device = None

    def getFrameRate(self):
        return self.imagesRead / (time.time() - self.startTime)

def getDeviceList():
    logging.info("Getting device list")
    devices=[]
    for i in range(4):
        logging.info("Getting properties for: %i" % i)
        try:
            device = Camera(i)
            devices.append((i, device.getProperties()["DisplayName"]))
            devices.close()
        except:
            pass
    return devices

if __name__ == '__main__':
    deviceList = getDeviceList()
    print 'found ', len(getDeviceList()) , 'video device(s) : '
    for d in deviceList:
        print d
    d = Camera(0)
    print d.device.getdisplayname()
    i = d.getImage()
    print type(i)
    #print i.histogram()
    i.save("junk.jpeg")

    #for i in range(100):
    #    x = d.getImage()
    #    print time.time()

    #print "Frame rate:", d.getFrameRate()
